package com.eportal.action;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.eportal.api.MdOpenApi;
import com.eportal.api.MdOpenBaseJson;
import com.eportal.api.MdOpenQryKeysJson.Key;
import com.eportal.base.BaseDAO;
import com.eportal.domain.Sysopt;
import com.eportal.domain.TAgent;
import com.eportal.domain.TCommunity;
import com.eportal.domain.TKeys;
import com.eportal.domain.TLock;
import com.eportal.domain.TUsers;
import com.eportal.service.InputComuService;
import com.eportal.service.SysOptService;
import com.eportal.service.TAgentService;
import com.eportal.service.TCommunityService;
import com.eportal.service.TKeysService;
import com.eportal.service.TLocksService;
import com.eportal.service.TUsersService;
import com.eportal.util.DateUtils;
import com.eportal.util.MD5;
	
public class InputComu extends BaseAction {
	@Resource(name = "dao")
	private BaseDAO dao;
	@Autowired
	private TAgentService tAgentService;
	@Autowired
	private InputComuService InputComuService;
	@Autowired
	private SysOptService sysOptService;
	@Autowired
	private TCommunityService tCommunityService;
	@Autowired
	private TKeysService tKeysService;

	@Autowired
	private TUsersService tUsersService;
	@Autowired
	private TLocksService tLocksService;
	@Autowired
	private TKeysService keysService;

	private Logger log = Logger.getLogger(InputComu.class.getName());
	private Map<String, Object> result = new HashMap<String, Object>();
	
	public String view() {
        return "view";
    }
	
    public void inputTest() throws IOException {
    	result = new HashMap<String, Object>();
		  String sql = new String("select t.*,app.appid,(select max(c.dm||','||c.described) from city c where c.described like '%'||t.shi||'%'||t.qu||'%') as citycode  from TMP_COMMUNITY t left join t10_appstore app on t.agtcode=app.agtcode ");
//		  String sql = new String("select t.*,app.appid,(select max(c.dm||','||c.described) from city c where c.described like '%'||t.shi||'%'||t.qu||'%') as citycode  from TMP_COMMUNITY t left join t10_appstore app on t.agtcode=app.agtcode where t.community='cdf75c4834a412058ec42601b6312c38' ");
		  List<Map<String, Object>> list = (List<Map<String, Object>>) InputComuService.getBySql(sql);
		  if (list.size()>0) {
			  TCommunity tCommunity;
			  int i = 0;
			  for (Map<String, Object> map : list) {
				  try {
					  tCommunity = new TCommunity();
					  tCommunity.setAgtCode(map.get("AGTCODE").toString());
					  tCommunity.setCommunityName(map.get("COMNAME").toString());
					  tCommunity.setDepartName(map.get("COMNAME").toString());
					  tCommunity.setInviteUrl("妙兜迁移，无注册码");
					  tCommunity.setDepartTel(map.get("USERNAME").toString());
					  tCommunity.setAdminUser(map.get("LOGIN_NAME").toString());
					  if(map.get("CITYCODE") !=null){
						  
						  String[] str = map.get("CITYCODE").toString().split(",");
						  //cityCode,查询
						  tCommunity.setAreaCode(str[0]);
						  
						  tCommunity.setCityCode(str[1]);
					  }
					  if(map.get("ADDRESS")!=null){
						  tCommunity.setStreet(map.get("ADDRESS").toString());
					  }
					  if(map.get("TRUENAME")!=null){
						  tCommunity.setComContact(map.get("TRUENAME").toString());
					  }
					  
					  tCommunity.setComm(map.get("PASSWORD").toString());
					  
					  tCommunity.setAppId(map.get("APPID").toString());
					  tCommunity.setType("1");
					  
					  //
					  tCommunity.setAddress(map.get("COMMUNITY").toString());
					  //同步到开发平台
					  result = tCommunityService.SyncTo(tCommunity);
					  if (!"1".equals(result.get("code").toString())) {
						  log.info("同步失败："+map.get("USERNAME"));
						  continue;
					  }
					  tCommunity.setType("0");
					  tCommunity.setPlatDepartId(result.get("departid").toString());
					  String roleId = "3";//社区未审核通过角色
					  
					  String status="1";//审核通过
					  //新建管理员用户并增加到表
					  result = InputComuService.addtCommunity(tCommunity,roleId,status);
					  if (!"1".equals(result.get("code").toString())) {
						  log.info("新建管理员失败："+map.get("USERNAME")+",原因："+result.get("msg"));
						  continue;
					  }
					  i++;
					  System.out.println("新建管理员成功,"+i+"个。："+map.get("USERNAME")+",姓名："+map.get("TRUENAME"));
				} catch (Exception e) {
					log.error("新建管理员失败："+map.get("USERNAME"),e);
					continue;
				}	
			  }
		  }
        responseBody(result);
    }
	

    public void inputUser() throws IOException {
    	result = new HashMap<String, Object>();
		try {
			int beginNum = 6000;
			int endNum = 7000;
			String sql = new String("select b.* from (select rownum rb,a.* from (select rownum rn,t.* from TMP_USER t ) a where rn<="+endNum+") b where rb>"+beginNum);
//			String sql = new String("select * from TMP_USER t where t.user_id='7892' ");
			List<Map<String, Object>> list = (List<Map<String, Object>>) InputComuService.getBySql(sql);
			Sysopt  user= (Sysopt)getSession().getAttribute("user");
			if (list.size()>0) {
				TUsers tUser;
				int i = 0;
				for (Map<String, Object> map : list) {
					try {
						
						StringBuffer where  = new StringBuffer();
						where.append(" tel= '");
						where.append(map.get("USERNAME").toString());
						where.append("' and appId= '");
						where.append(map.get("APPID").toString());
						where.append("'");
						
						tUser = tUsersService.getByWhere(where.toString());
						if (tUser != null) {
							log.info("app用户已存在："+map.get("USERNAME")+",appID："+map.get("APPID").toString());
							continue;
						}
						tUser = new TUsers();
						tUser.setAgtCode(map.get("AGTCODE").toString()); 
						//需要创建
						tUser.setUserId(tUsersService.getUserID());	
						tUser.setAppId(map.get("APPID").toString());
						tUser.setTel(map.get("USERNAME").toString());	 
						tUser.setPasswd(MD5.MD5Encode(map.get("PASSWORD").toString()));		
						String user_id = map.get("USER_ID").toString();
						tUser.setProfession(user_id);	//保存临时表的userid		 
						tUser.setAuTel(map.get("USERNAME").toString());	
						if (map.get("NAME") != null) {
							tUser.setAuName(map.get("NAME").toString());
						}
						tUser.setcUserName(user.getSid().toString());
						tUser.setcTime(new Timestamp(Long.valueOf(map.get("ADD_TIME")+"000")));
						try {
							tUsersService.add(tUser);
						} catch (Exception e) {
							log.info("新建用户失败："+map.get("USERNAME"),e);
							log.error(this, e);
							continue;
						}
						i++;
						System.out.println("新建用户成功,"+i+"个。："+map.get("USERNAME"));
					} catch (Exception e) {
						log.info("新建用户失败："+map.get("USERNAME"),e);
						log.error(this, e);
						continue;
					}
				}
			}
		} catch (Exception e) {
			log.error("新建用户失败：出现异常",e);
		}  
        responseBody(result);
    }
	
    public void inputUserComu() throws IOException {
    	result = new HashMap<String, Object>();
    	int beginNum = 6000;
		int endNum = 7000;
		String sql = new String("select b.* from (select rownum rb,a.* from (select rownum rn,t.*,u.userid,c.sid from TMP_USER_COMMUNITY t left join T04_USERS u on t.user_id=u.profession left join t03_community c on t.community=c.address ) a where rn<="+endNum+") b where rb>"+beginNum);
//		  String sql = new String("select t.*,u.userid,c.sid,uc.sid as ucsid from TMP_USER_COMMUNITY t left join T04_USERS u on t.user_id=u.profession  left join t03_community c on t.community=c.address left join t04_users_community uc on (u.userid=uc.userid and c.sid=uc.communityid) where uc.sid is null");
		  List<Map<String, Object>> list = (List<Map<String, Object>>) InputComuService.getBySql(sql);
		  Sysopt  user= (Sysopt)getSession().getAttribute("user");
		  if (list.size()>0) {
			  int i = 0;
			  for (Map<String, Object> map : list) {
				  try {
					  if (map.get("USERID") == null || map.get("SID") == null) {
						  log.info("失败，根据app用户社区关系中找不到usr或者comunityId，"+map.get("USER_ID")+",cumu："+map.get("COMMUNITY"));
						  continue;
					  }
					  tUsersService.updateUsersCommunity(map.get("SID").toString(),0L,map.get("USERID").toString());
					  i++;
					  System.out.println("新建用户社区关系成功,"+i+"个。："+map.get("USER_ID")+",cumu："+map.get("COMMUNITY"));
				} catch (Exception e) {
					log.error("失败，"+map.get("USER_ID")+",cumu："+map.get("COMMUNITY"),e);
					continue;
				}
			}
		  }
        responseBody(result);
    }
    
    public void inputKey() throws IOException {
		result = new HashMap<String, Object>();
		
			int beginNum = 24000;
			int endNum = 27000;
//				beginNum = endNum+1;
//				endNum = beginNum + 1000 -1;
				
				String sql = new String("select b.* from (select rownum rb,a.* from (select rownum rn,t.* from TMP_KEYS t ) a where rn<="+endNum+") b where rb>"+beginNum);
//				String sql = new String("select rownum rn,t.* from TMP_KEYS t where t.pid='BLZXB150400134' and t.mobile='18957296260'");
				List<Map<String, Object>> list = (List<Map<String, Object>>) InputComuService.getBySql(sql);
				int yes = 0;
				int no = 0;
				if (list.size() > 0) {
					for (Map<String, Object> map : list) {
						try {
						log.info("正在导入 pid='" + map.get("PID")+"'");
						TCommunity community = tCommunityService.get("ADDRESS='" + map.get("COMMUNITY") + "'");
						TUsers users = tUsersService.getByWhere("PROFESSION='"+map.get("USER_ID")+"'");
						if(users!=null){
							
							TLock lock = tLocksService.getHql("pid='" + map.get("PID")+"'");
							if (lock == null) {
								no++;
								log.error("钥匙失败,累计："+no+"个。锁不存在,pid=" + map.get("PID"));
								continue;
							}
							Date valid_ = DateUtils.stringToDate((String)map.get("VALIDITY"), "yyyyMMdd");
							Date now = DateUtils.stringToDate(DateUtils.formatDatetime(new Date(), "yyyyMMdd"), "yyyyMMdd");
							if (community == null) {
								no++;
								log.error("钥匙失败,累计："+no+"个。社区不存在,community=" + map.get("COMMUNITY"));
								continue;
							}
							if(valid_.after(now)){
								TAgent agent = tAgentService.get(users.getAgtCode());
								TKeys keys = tKeysService.getTKeys(users.getUserId(),(String)map.get("PID"));
								if(keys != null){
									Date validity = keys.getValidity();
									if(valid_.after(validity)){
										keys.setStatus("0");
										keys.setValidity(new Timestamp(valid_.getTime()));
										Map<String, Object>  m = MdOpenApi.qeyKeys((String)map.get("PID"), agent.getPlatAgtcode(), agent.getPlatAppKey(), users.getTel(),(String) map.get("VALIDITY"));
										if("0".equals(m.get("code"))){
											List<Key> klist = (List<Key>)m.get("list");
											keys.setPlatKeyId(klist.get(0).getKsid());
											keys.setKeyContent(klist.get(0).getLock_id());
											keys.setPlatDepartid(klist.get(0).getCommunity());
											keys.setAlgorithmVer(klist.get(0).getAlgorithmVer());
											keysService.update(keys);
											yes++;
											log.info("钥匙成功,累计："+yes+"个。手机："+map.get("USER_ID")+",pid:"+map.get("PID"));
										}else{
											no++;
											log.error("钥匙失败,累计："+no+"个。qryKeys fail.errmsg=" + m.toString());
										}
									}else{
										no++;
										log.info("钥匙失败,累计："+no+"个。钥匙已存在，但有效期不足以覆盖，手机："+map.get("MOBILE")+"pid:"+map.get("PID"));
										continue;
									}
								}else{
									keys = new TKeys();
									keys.setPid((String)map.get("PID"));
									keys.setReqTime(new Timestamp(System.currentTimeMillis()));
									keys.setValidity(new Timestamp(valid_.getTime()));
									keys.setLockName(lock.getInstallLockName());
									keys.setStatus("0");
									keys.setCommunityId(community.getSid().toString());
									keys.setUserId(users.getUserId());
									Map<String, Object>  m = MdOpenApi.qeyKeys((String)map.get("PID"), agent.getPlatAgtcode(), agent.getPlatAppKey(), users.getTel(),(String) map.get("VALIDITY"));
									if("0".equals(m.get("code"))){
										List<Key> klist = (List<Key>)m.get("list");
										keys.setPlatKeyId(klist.get(0).getKsid());
										keys.setKeyContent(klist.get(0).getLock_id());
										keys.setPlatDepartid(klist.get(0).getCommunity());
										keys.setAlgorithmVer(klist.get(0).getAlgorithmVer());
										keysService.add(keys);
										yes++;
										log.info("钥匙成功,累计："+yes+"个。手机："+map.get("USER_ID")+",pid:"+map.get("PID"));
									}else{
										no++;
										log.error("钥匙失败,累计："+no+"个。errmsg=" + m.toString());
									}
								}
							}else{
								no++;
								log.error("钥匙失败,累计："+no+"个。valid_ 非法，pid="+map.get("PID")+",userid="+map.get("USER_ID")+",validty="+map.get("VALIDITY"));
							}
							
						}else{
							no++;
							log.error("钥匙失败,累计："+no+"个。users is null,PROFESSION="+map.get("USER_ID"));
						}
					} catch (Exception e) {
						no++;
						log.error("钥匙失败,累计："+no+"个。出现异常"+map.get("USER_ID"),e);
					}	
						
					}
				}
			
		

		responseBody(result);
	}
	
	
	public void inputLock() throws IOException {
		result = new HashMap<String, Object>();
		int yes = 0;
		int no = 0;
		int beginNum = 3000;
		int endNum = 4000;
		String sql = new String("select b.* from (select rownum rb,a.* from (select rownum rn,t.* from TMP_LOCKS t ) a where rn<="+endNum+") b where rb>"+beginNum);
//		String sql = new String("select * from TMP_LOCKS t where t.pid='GDGZ0076'");
		List<Map<String, Object>> list = (List<Map<String, Object>>) InputComuService.getBySql(sql);
		if (list.size() > 0) {
			for (Map<String, Object> map : list) {
				try {
				log.info("正在导入 pid='" + map.get("PID")+"'");
				TLock lock = tLocksService.getHql("pid='" + map.get("PID")+"'");
				if (lock != null) {
					no++;
					log.info("安装失败,累计："+no+"个。锁已存在，不处理" + map.get("PID"));
					continue;
				}
				lock = new TLock();
				TCommunity community = null;
				TAgent agent = tAgentService.get((String)map.get("AGTCODE"));
				if(map.get("LOCK_NAME")==null){//未在妙兜安装的
					
				}else{
					community = tCommunityService.get("ADDRESS='" + map.get("COMMUNITY") + "'");
				}
//				if(community==null){//未在妙兜安装的
//						community= tCommunityService.get("type='1' and agtcode='"+agent.getAgtCode()+"'");
//					yes++;
//					log.info("安装成功,累计："+yes+"个。锁未安装，不处理" + map.get("PID"));
//					continue;
//				}
				
				if (agent == null) {
					no++;
					log.error("安装失败,累计："+no+"个，agent is null,agtcode=" + map.get("AGTCODE"));
					continue;
				}
				
				if (lock.getSid() == null) {
					//未安装，在妙兜的
					lock.setAgtCode((String)map.get("AGTCODE"));
					lock.setPid((String)map.get("PID"));
					lock.setCheckCode("");
					lock.setCheckStatus("0");
					lock.setType("0");
					if(StringUtils.isBlank((String)map.get("COMMUNITY"))){
						lock.setStatus("-1");// 未安装
						tLocksService.add(lock);
						yes++;
						log.info("安装成功，累计："+yes+"个，pid:" +map.get("PID"));
					}else{
						lock.setStatus("1");// 已安装
						lock.setCommunityId(community.getSid().toString());
						lock.setInstallLockName((String)map.get("LOCK_NAME"));
						lock.setInstallWork("1");
						lock.setInstallTime(new Timestamp(System.currentTimeMillis()));
						lock.setIsPubUnit("1");
						lock.setIntallComm("迁移妙兜硬件，安装硬件PID编号："+(String)map.get("PID")+" 到  "+community.getCommunityName()+"， 共一个。");
						MdOpenBaseJson json = MdOpenApi.installLock(lock, agent.getPlatAgtcode(), agent.getPlatAppKey(),
								community.getPlatDepartId());
						if (json.isSuccess()) {
							tLocksService.add(lock);
							yes++;
							log.info("安装成功，累计："+yes+"个，pid:" +map.get("PID"));
						} else {
							no++;
							log.error("安装失败,累计："+no+"个，errmsg=" + json.getMsg().toString());
						}
					}
				} else {
					no++;
					log.error("安装失败,累计："+no+"个。锁在数据库中已存在" + map.get("PID"));
				}
				} catch (Exception e) {
					no++;
					log.error("安装失败,累计："+no+"个。出现异常", e);
				}
			}
		}else{
			log.error("安装失败,查询无数据");
		}
		responseBody(result);
	}
	
	
	public void inputLock4open() throws IOException {
		result = new HashMap<String, Object>();
		try {
			String sql = new String("select t.* from TMP_LOCKS t where agtcode='1492'");
			List<Map<String, Object>> list = (List<Map<String, Object>>) InputComuService.getBySql(sql);
			if (list.size() > 0) {
				System.out.println("---------------------");
				String where = "";
				for (Map<String, Object> map : list) {
					TAgent agent = tAgentService.get((String)map.get("AGTCODE"));
					String str = "update tlock set agtcode='"+agent.getPlatAgtcode()+"' where pid='"+(String)map.get("PID")+"' and agtcode='10002';";
					System.out.println(str);
					where +=" pid='"+(String)map.get("pid")+"' or";
				}
				System.out.println(where);
			}
		} catch (Exception e) {
			log.error(this, e);
		}

		responseBody(result);
	}

}
